<?php

/**
 * 顺序栈,使用数组实现,需要记录栈顶和栈底
 */
class SequenceStack {
    public $data;
    public $top; //栈顶, 栈底默认为-1
}

/**
 * 初始化栈
 * @return SequenceStack
 */
function InitSqStack() {
    $stack = new SequenceStack();
    $stack->data = [];
    $stack->top = -1;
    return $stack;
}

/**
 * 入栈操作
 * @param SequenceStack $stack
 * @param $x
 */
function PushSqStack(SequenceStack &$stack, $x) {
    $stack->top++;
    $stack->data[$stack->top] = $x;
}

/**
 * 出栈操作
 * @param SequenceStack $stack
 * @return bool
 */
function PopSqStack(SequenceStack &$stack) {
    // 栈空
    if ($stack->top == -1) {
        return false;
    }

    $v = $stack->data[$stack->top];
    unset($stack->data[$stack->top]);
    $stack->top--;
    return $v;
}

$stack = InitSqStack();

PushSqStack($stack, 'a'); //入栈,下同
PushSqStack($stack, 'b');
PushSqStack($stack, 'c');

print_r($stack);
/*
SqStack Object
(
    [data] => Array
        (
            [0] => a
            [1] => b
            [2] => c
        )

    [top] => 2 //当前栈顶的index
)
*/

echo PopSqStack($stack), PHP_EOL; // c (出栈,下同)
echo PopSqStack($stack), PHP_EOL; // b
echo PopSqStack($stack), PHP_EOL; // a

print_r($stack);

/*
SqStack Object
(
    [data] => Array
        (
        )

    [top] => -1
)
*/

echo "================================================== \n";

// PHP自带的 array_push 和 array_pop 实现的就是一个顺序栈
$sqStackList = [];
array_push($sqStackList, 'a'); //入栈,下同
array_push($sqStackList, 'b');
array_push($sqStackList, 'c');
print_r($sqStackList);
/*
Array
(
    [0] => a
    [1] => b
    [2] => c
)
*/

array_pop($sqStackList); //出栈
print_r($sqStackList);
/*
Array
(
    [0] => a
    [1] => b
)
*/
